package com.value.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.value.model.AnnotationXmlBean;
import com.value.model.FormBean;
import com.value.util.FullBean;

public class MainServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String preUrl = "WEB-INF/view/";
		String url = "";
		String path = request.getServletPath().split("\\.")[0];
		if(path==null||"".equals(path.trim())){
			url="404.jsp";
		}
		Map<String, AnnotationXmlBean> map = (Map<String, AnnotationXmlBean>) this
				.getServletContext().getAttribute("annotationMap");
		AnnotationXmlBean sxb = map.get(path);
		if(sxb==null){
			url = "404.jsp";
		}
		FormBean bean = FullBean.full(request,sxb.getFormClass());
		ActionForm action = null;
		if("".equals(url)){
			try {
				Class clazz = Class.forName(sxb.getActionType());
				action = (ActionForm) clazz.newInstance();
				url = action.execute(request,response, bean);
				url = preUrl+url+".jsp";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		PrintWriter out = response.getWriter();
		out.print("开始响应....");
		RequestDispatcher rd = request.getRequestDispatcher(url);
		rd.forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

}
